<template>
  <div class="product-integrated-edit">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="card-header__titles">
            <h1 class="card-title">{{ pageTitle || (isEdit ? '编辑产品' : '创建产品') }}</h1>
            <p v-if="pageSubtitle" class="card-subtitle">{{ pageSubtitle }}</p>
          </div>
          <el-button @click="$router.back()">返回</el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="140px"
        label-position="left"
      >
        <!-- 基本信息 -->
        <div class="section-card basic-info-section">
          <div class="section-header">
            <h3 class="section-title">
              <el-icon><Document /></el-icon>
              基本信息
            </h3>
            <p class="section-subtitle">设置产品的基础信息和分类</p>
          </div>
        
        <el-form-item label="分类" prop="category_slugs">
          <el-select v-model="form.category_slugs" placeholder="请选择分类" multiple collapse-tags>
            <el-option
              v-for="cat in categories"
              :key="cat.slug"
              :label="cat.name"
              :value="cat.slug"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="封面图" prop="cover_image">
          <el-upload
            class="image-uploader clickable-upload"
            :show-file-list="false"
            :on-change="handleCoverImageChange"
            :auto-upload="false"
            accept="image/*"
          >
            <div class="upload-area">
              <img v-if="coverImagePreview" :src="coverImagePreview" class="image-preview" />
              <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
            </div>
          </el-upload>
          <div class="image-tip">建议尺寸：800x800px</div>
        </el-form-item>

        <el-form-item label="悬停图（可选）">
          <el-upload
            class="image-uploader clickable-upload"
            :show-file-list="false"
            :on-change="handleHoverImageChange"
            :auto-upload="false"
            accept="image/*"
          >
            <div class="upload-area">
              <img v-if="hoverImagePreview" :src="hoverImagePreview" class="image-preview" />
              <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
            </div>
          </el-upload>
          <div class="image-tip">鼠标悬停时显示的图片</div>
        </el-form-item>

        <el-form-item label="排序">
          <el-input-number v-model="form.sort_order" :min="0" />
        </el-form-item>

        <el-form-item label="状态">
          <el-switch v-model="form.is_active" />
        </el-form-item>

        <el-form-item label="标签">
          <el-checkbox v-model="form.tag_new">新品</el-checkbox>
          <el-checkbox v-model="form.tag_hot">热门</el-checkbox>
          <el-checkbox v-model="form.tag_featured">精选</el-checkbox>
        </el-form-item>
        </div>

        <!-- 多语言翻译 -->
        <div class="section-card translation-section">
          <div class="section-header">
            <h3 class="section-title">
              <el-icon><Promotion /></el-icon>
              产品信息（多语言）
            </h3>
            <p class="section-subtitle">为不同语言设置产品名称和描述</p>
          </div>
        
        <el-tabs v-model="activeLocale" type="border-card">
          <el-tab-pane
            v-for="locale in locales"
            :key="locale.code"
            :label="locale.name"
            :name="locale.code"
          >
            <el-form-item :label="`产品名称 (${locale.name})`">
              <el-input v-model="form.translations[locale.code].name" placeholder="请输入产品名称" />
            </el-form-item>

            <el-form-item :label="`简短描述 (${locale.name})`">
              <el-input
                v-model="form.translations[locale.code].short_desc"
                type="textarea"
                :rows="3"
                placeholder="请输入简短描述"
              />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
        </div>

        <!-- 产品变体 -->
        <div class="section-card variants-main-section">
          <div class="section-header">
            <h3 class="section-title">
              <el-icon><Grid /></el-icon>
              产品变体
            </h3>
            <p class="section-subtitle">配置产品的不同规格、价格和库存</p>
          </div>
        
        <div class="variants-section">
          <el-button type="primary" @click="addVariant" style="margin-bottom: 20px;">
            <el-icon><Plus /></el-icon>
            添加变体
          </el-button>

          <el-collapse v-model="activeVariants" accordion>
            <el-collapse-item
              v-for="(variant, index) in form.variants"
              :key="index"
              :name="index"
            >
              <template #title>
                <div class="variant-title">
                  <span>变体 #{{ index + 1 }}</span>
                  <span v-if="variant.option_values.length > 0" class="variant-options">
                    ({{ getVariantOptionText(variant) }})
                  </span>
                  <el-button
                    type="danger"
                    size="small"
                    @click.stop="removeVariant(index)"
                    style="margin-left: auto;"
                  >
                    删除
                  </el-button>
                </div>
              </template>

              <!-- 变体选项 -->
              <div class="variant-options-section">
                <div class="subsection-header">
                  <h4><el-icon><Setting /></el-icon> 选项配置</h4>
                  <el-button type="primary" size="small" @click="addVariantOption(index)">
                    <el-icon><Plus /></el-icon>
                    添加选项
                  </el-button>
                </div>

                <div
                  v-for="(option, optIndex) in variant.option_values"
                  :key="optIndex"
                  class="option-item"
                >
                  <el-select
                    v-model="option.option_type"
                    placeholder="选项类型"
                    style="width: 150px; margin-right: 10px;"
                  >
                    <el-option
                      v-for="type in optionTypes"
                      :key="type.option_type"
                      :label="type.display_name"
                      :value="type.option_type"
                    />
                  </el-select>

                  <el-input
                    v-model="option.value"
                    placeholder="选项值"
                    style="width: 200px; margin-right: 10px;"
                  />

                  <el-input
                    v-if="option.option_type === 'color'"
                    v-model="option.color_code"
                    placeholder="颜色代码 #RRGGBB"
                    style="width: 150px; margin-right: 10px;"
                  />

                  <el-button
                    type="danger"
                    size="small"
                    @click="removeVariantOption(index, optIndex)"
                  >
                    删除
                  </el-button>
                </div>
              </div>

              <!-- 变体基本信息 -->
              <el-form-item label="SKU编码" style="margin-top: 20px;">
                <el-input v-model="variant.sku" placeholder="可选" />
              </el-form-item>

              <el-form-item label="价格" required>
                <el-input-number
                  v-model="variant.price"
                  :min="0"
                  :precision="2"
                  :step="0.01"
                />
              </el-form-item>

              <el-form-item label="库存" required>
                <el-input-number v-model="variant.stock" :min="0" />
              </el-form-item>

              <el-form-item label="产品详情">
                <el-input
                  v-model="variant.product_details"
                  type="textarea"
                  :rows="3"
                  placeholder="该变体的特定产品详情（可选）"
                />
              </el-form-item>

              <el-form-item label="状态">
                <el-switch v-model="variant.is_active" />
              </el-form-item>

              <!-- 变体图片 -->
              <el-form-item label="变体图片">
                <div class="variant-images">
                  <div class="variant-image-grid">
                    <div
                      v-for="(image, imgIndex) in variant.images"
                      :key="imgIndex"
                      class="variant-image-item"
                      :class="{ primary: image.is_primary }"
                    >
                      <el-upload
                        class="image-uploader clickable-upload"
                        :show-file-list="false"
                        :auto-upload="false"
                        accept="image/*"
                        :on-change="(file: any) => handleVariantImageReplace(file, index, imgIndex)"
                      >
                        <div class="upload-area">
                          <img v-if="image.url" :src="image.url" class="image-preview" />
                          <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
                        </div>
                      </el-upload>
                      <div class="variant-image-actions">
                        <el-button
                          type="primary"
                          size="small"
                          plain
                          :disabled="image.is_primary"
                          @click="setVariantPrimary(index, imgIndex)"
                        >
                          {{ image.is_primary ? '主图' : '设为主图' }}
                        </el-button>
                        <el-button
                          type="danger"
                          size="small"
                          plain
                          @click="removeVariantImage(index, imgIndex)"
                        >
                          删除
                        </el-button>
                      </div>
                    </div>

                    <el-upload
                      class="image-uploader clickable-upload add-card"
                      :show-file-list="false"
                      :auto-upload="false"
                      accept="image/*"
                      :on-change="(file: any) => handleVariantImageAdd(file, index)"
                    >
                      <div class="upload-area">
                        <el-icon class="image-uploader-icon"><Plus /></el-icon>
                      </div>
                    </el-upload>
                  </div>
                </div>
              </el-form-item>

              <!-- 变体规格 -->
              <div class="variant-specifications-section">
                <div class="subsection-header">
                  <h4><el-icon><List /></el-icon> 变体规格</h4>
                  <el-button type="primary" size="small" plain @click="addVariantSpecification(index)">
                    <el-icon><Plus /></el-icon>
                    添加规格
                  </el-button>
                </div>
              <div class="variant-specifications">

                <div v-if="variant.specifications && variant.specifications.length > 0" class="spec-list">
                  <div
                    v-for="(spec, specIndex) in variant.specifications"
                    :key="specIndex"
                    class="spec-item-row"
                  >
                    <el-input
                      v-model="spec.key"
                      placeholder="规格名称（如：重量）"
                      class="spec-input"
                    />
                    <el-input
                      v-model="spec.value"
                      placeholder="规格值（如：2kg）"
                      class="spec-input"
                    />
                    <el-button
                      type="danger"
                      size="small"
                      plain
                      @click="removeVariantSpecification(index, specIndex)"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
                <div v-else class="spec-empty">暂无规格，点击上方按钮添加</div>
              </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        </div>

        <!-- 提交按钮 -->
        <el-form-item style="margin-top: 30px;">
          <el-button type="primary" :loading="loading" @click="handleSubmit" size="large">
            {{ loading ? '保存中...' : '保存产品' }}
          </el-button>
          <el-button @click="$router.back()" size="large">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules, type UploadFile } from 'element-plus'
import { Plus, Document, Promotion, Grid, Setting, List } from '@element-plus/icons-vue'
import {
  getProductIntegrated,
  createProductIntegrated,
  updateProductIntegrated,
  getCategories,
  getOptionTypes,
  uploadVariantImage,
  type ProductIntegrated,
  type ProductVariant,
  type Category,
  type OptionType
} from '@/api/productIntegrated'
import { usePageMeta } from '@/composables/usePageMeta'

const route = useRoute()
const router = useRouter()

const { pageTitle, pageSubtitle } = usePageMeta()

const formRef = ref<FormInstance>()
const loading = ref(false)
const isEdit = ref(false)

// 分类和选项类型
const categories = ref<Category[]>([])
const optionTypes = ref<OptionType[]>([])

// 语言列表
const locales = [
  { code: 'zh', name: '中文' },
  { code: 'en', name: 'English' },
  { code: 'de', name: 'Deutsch' },
  { code: 'nl', name: 'Nederlands' },
  { code: 'fr', name: 'Français' }
]
const activeLocale = ref('zh')
const activeVariants = ref<number[]>([])  // 默认为空数组，所有变体都折叠

// 图片预览
const coverImagePreview = ref('')
const hoverImagePreview = ref('')

// 表单数据
const form = reactive<any>({
  category_slugs: [],
  is_active: true,
  sort_order: 0,
  tag_new: false,
  tag_hot: false,
  tag_featured: false,
  translations: {
    zh: { name: '', short_desc: '', rich_desc: '' },
    en: { name: '', short_desc: '', rich_desc: '' },
    de: { name: '', short_desc: '', rich_desc: '' },
    nl: { name: '', short_desc: '', rich_desc: '' },
    fr: { name: '', short_desc: '', rich_desc: '' }
  },
  variants: []
})

// 表单验证规则
const rules: FormRules = {
  category_slugs: [{ required: true, message: '请选择至少一个分类', trigger: 'change', type: 'array', min: 1 }]
}

// 获取变体选项文本
const getVariantOptionText = (variant: ProductVariant) => {
  return variant.option_values.map(opt => `${opt.option_type}: ${opt.value}`).join(', ')
}

// 添加变体
const addVariant = () => {
  const newVariant = {
    option_values: [],
    price: 0,
    stock: 0,
    is_active: true,
    sort_order: form.variants.length,
    images: [],
    specifications: []
  }
  form.variants.push(newVariant)
  normalizeVariantImages(newVariant)
  normalizeVariantSpecifications(newVariant)
  activeVariants.value = form.variants.length - 1
}

// 删除变体
const removeVariant = (index: number) => {
  form.variants.splice(index, 1)
}

// 添加变体选项
const addVariantOption = (variantIndex: number) => {
  form.variants[variantIndex].option_values.push({
    option_type: 'size',
    value: ''
  })
}

// 删除变体选项
const removeVariantOption = (variantIndex: number, optionIndex: number) => {
  form.variants[variantIndex].option_values.splice(optionIndex, 1)
}

// 处理封面图上传
const handleCoverImageChange = (file: UploadFile) => {
  if (file.raw) {
    form.cover_image = file.raw
    coverImagePreview.value = URL.createObjectURL(file.raw)
  }
}

// 处理悬停图上传
const handleHoverImageChange = (file: UploadFile) => {
  if (file.raw) {
    form.hover_image = file.raw
    hoverImagePreview.value = URL.createObjectURL(file.raw)
  }
}

const normalizeVariantImages = (variant: any) => {
  if (!variant.images) return
  const images = variant.images
  images.forEach((img: any, idx: number) => {
    img.sort_order = idx
    if (typeof img.is_primary === 'undefined') {
      img.is_primary = idx === 0
    }
  })

  if (!images.some((img: any) => img.is_primary) && images[0]) {
    images[0].is_primary = true
  }
}

const normalizeVariantSpecifications = (variant: any) => {
  if (!variant.specifications) return
  variant.specifications.forEach((spec: any, idx: number) => {
    spec.sort_order = spec.sort_order ?? idx
    if (typeof spec.is_active === 'undefined') {
      spec.is_active = true
    }
  })
}

// 处理新增变体图片
const handleVariantImageAdd = async (file: UploadFile, variantIndex: number) => {
  if (!file.raw) return

  try {
    loading.value = true
    const result = await uploadVariantImage(file.raw)
    
    if (!form.variants[variantIndex].images) {
      form.variants[variantIndex].images = []
    }
    const images = form.variants[variantIndex].images!
    const hasPrimary = images.some(img => img.is_primary)
    images.push({
      url: result.url,
      path: result.path,
      sort_order: images.length,
      is_primary: hasPrimary ? false : true
    })
    normalizeVariantImages(form.variants[variantIndex])
    
    ElMessage.success('图片上传成功')
  } catch (error) {
    ElMessage.error('图片上传失败')
  } finally {
    loading.value = false
  }
}

// 替换已有变体图片
const handleVariantImageReplace = async (file: UploadFile, variantIndex: number, imageIndex: number) => {
  if (!file.raw) return

  try {
    loading.value = true
    const result = await uploadVariantImage(file.raw)

    const images = form.variants[variantIndex].images
    if (!images || !images[imageIndex]) return

    images[imageIndex] = {
      ...images[imageIndex],
      url: result.url,
      path: result.path
    }
    normalizeVariantImages(form.variants[variantIndex])

    ElMessage.success('图片替换成功')
  } catch (error) {
    ElMessage.error('图片替换失败')
  } finally {
    loading.value = false
  }
}

// 删除变体图片
const removeVariantImage = (variantIndex: number, imageIndex: number) => {
  const images = form.variants[variantIndex].images
  if (!images) return

  images.splice(imageIndex, 1)

  images.forEach((img: any, idx: number) => {
    img.sort_order = idx
  })

  normalizeVariantImages(form.variants[variantIndex])
}

// 设置主图
const setVariantPrimary = (variantIndex: number, imageIndex: number) => {
  const images = form.variants[variantIndex].images
  if (!images) return

  images.forEach((img: any, idx: number) => {
    img.is_primary = idx === imageIndex
  })
}

const addVariantSpecification = (variantIndex: number) => {
  if (!form.variants[variantIndex].specifications) {
    form.variants[variantIndex].specifications = []
  }
  form.variants[variantIndex].specifications.push({
    key: '',
    value: '',
    sort_order: form.variants[variantIndex].specifications.length,
    is_active: true
  })
  normalizeVariantSpecifications(form.variants[variantIndex])
}

const removeVariantSpecification = (variantIndex: number, specIndex: number) => {
  const specs = form.variants[variantIndex].specifications
  if (!specs) return
  specs.splice(specIndex, 1)
  normalizeVariantSpecifications(form.variants[variantIndex])
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) return

    // 验证至少有一个变体
    if (form.variants.length === 0) {
      ElMessage.error('请至少添加一个产品变体')
      return
    }

    // 验证每个变体都有价格和库存
    for (let i = 0; i < form.variants.length; i++) {
      const variant = form.variants[i]
      if (variant.price === undefined || variant.price < 0) {
        ElMessage.error(`变体 #${i + 1} 的价格无效`)
        return
      }
      if (variant.stock === undefined || variant.stock < 0) {
        ElMessage.error(`变体 #${i + 1} 的库存无效`)
        return
      }
    }

    loading.value = true
    try {
      // 构建FormData
      const formData = new FormData()

      // 添加基本字段
      formData.append('category_slugs', JSON.stringify(form.category_slugs))
      formData.append('is_active', String(form.is_active))
      formData.append('sort_order', String(form.sort_order))
      formData.append('tag_new', String(form.tag_new))
      formData.append('tag_hot', String(form.tag_hot))
      formData.append('tag_featured', String(form.tag_featured))

      // 添加图片
      if (form.cover_image instanceof File) {
        formData.append('cover_image', form.cover_image)
      }
      if (form.hover_image instanceof File) {
        formData.append('hover_image', form.hover_image)
      }

      // 添加翻译（JSON格式）
      formData.append('translations', JSON.stringify(form.translations))

      // 添加变体（JSON格式）
      const normalizedVariants = form.variants.map((variant: any, index: number) => {
        const images = (variant.images || []).map((img: any, imgIndex: number) => ({
          url: img.url,
          path: img.path || '',
          sort_order: img.sort_order ?? imgIndex,
          is_primary: img.is_primary ?? imgIndex === 0
        }))

        const specifications = (variant.specifications || [])
          .map((spec: any, specIndex: number) => ({
            key: (spec.key || '').trim(),
            value: (spec.value || '').trim(),
            sort_order: spec.sort_order ?? specIndex,
            is_active: spec.is_active ?? true
          }))
          .filter((spec: any) => spec.key !== '' && spec.value !== '')

        return {
          ...variant,
          sort_order: variant.sort_order ?? index,
          images,
          specifications
        }
      })

      formData.append('variants', JSON.stringify(normalizedVariants))

      if (isEdit.value) {
        await updateProductIntegrated(Number(route.params.id), formData)
        ElMessage.success('更新成功')
      } else {
        await createProductIntegrated(formData)
        ElMessage.success('创建成功')
      }

      router.push('/products-integrated')
    } catch (error: any) {
      console.error('保存失败:', error)
      ElMessage.error(error.response?.data?.message || '保存失败')
    } finally {
      loading.value = false
    }
  })
}

// 加载分类和选项类型
const loadMetadata = async () => {
  try {
    console.log('开始加载元数据')
    const [cats, types] = await Promise.all([
      getCategories(),
      getOptionTypes()
    ])
    console.log('分类数据:', cats)
    console.log('选项类型:', types)
    categories.value = cats
    optionTypes.value = types
  } catch (error) {
    console.error('加载元数据失败:', error)
    ElMessage.error('加载元数据失败')
    throw error
  }
}

// 加载产品数据（编辑模式）
const loadProduct = async (id: number) => {
  try {
    loading.value = true
    console.log('开始加载产品数据, ID:', id)
    const product = await getProductIntegrated(id)
    console.log('产品数据加载成功:', product)

    // 填充表单 - 修复分类为数组
    if (product.categories_data && product.categories_data.length > 0) {
      form.category_slugs = product.categories_data.map(cat => cat.slug)
    } else if (product.category) {
      form.category_slugs = [product.category.slug]
    } else {
      form.category_slugs = []
    }
    form.is_active = product.is_active
    form.sort_order = product.sort_order || 0
    form.tag_new = product.tag_new || false
    form.tag_hot = product.tag_hot || false
    form.tag_featured = product.tag_featured || false

    // 填充翻译 - 确保所有语言都有默认值
    if (product.translations_data) {
      console.log('翻译数据:', product.translations_data)
      // 合并后端数据和默认值，确保所有语言都存在
      locales.forEach(locale => {
        if (product.translations_data![locale.code]) {
          form.translations[locale.code] = {
            name: product.translations_data![locale.code].name || '',
            short_desc: product.translations_data![locale.code].short_desc || '',
            rich_desc: product.translations_data![locale.code].rich_desc || ''
          }
        }
      })
    }

    // 填充变体
    if (product.variants_data) {
      console.log('变体数据:', product.variants_data)
      form.variants = product.variants_data.map(v => {
        const priceValue = Number(v.price)
        const stockValue = Number(v.stock)
        return {
          id: v.id,
          sku: v.sku || '',
          option_values: (v.option_values || []).map(opt => ({
            option_type: opt.option_type,
            value: opt.value,
            color_code: opt.color_code || '',
            translations: opt.translations || {}
          })),
          price: Number.isFinite(priceValue) ? priceValue : 0,
          stock: Number.isFinite(stockValue) ? stockValue : 0,
          product_details: v.product_details || '',
          is_active: v.is_active ?? true,
          sort_order: v.sort_order ?? 0,
          images: (v.images || []).map((img, idx) => ({
            id: img.id,
            url: img.url,
            path: img.path || '',
            sort_order: img.sort_order ?? idx,
            is_primary: img.is_primary ?? idx === 0
          })),
          specifications: (v.specifications || []).map((spec, specIdx) => ({
            key: spec.key || '',
            value: spec.value || '',
            sort_order: spec.sort_order ?? specIdx,
            is_active: spec.is_active ?? true
          }))
        }
      })
      form.variants.forEach((variant: any) => {
        normalizeVariantImages(variant)
        normalizeVariantSpecifications(variant)
      })
    }

    // 设置图片预览
    if (product.cover_image_url) {
      coverImagePreview.value = product.cover_image_url
    }
    if (product.hover_image_url) {
      hoverImagePreview.value = product.hover_image_url
    }

    console.log('产品数据填充完成')
  } catch (error: any) {
    console.error('加载产品失败:', error)
    ElMessage.error(error.response?.data?.message || '加载产品失败')
    router.back()
  } finally {
    console.log('设置 loading = false')
    loading.value = false
  }
}

onMounted(async () => {
  try {
    console.log('组件挂载，开始加载数据')
    await loadMetadata()
    console.log('元数据加载完成')

    const id = route.params.id
    if (id) {
      console.log('编辑模式，产品 ID:', id)
      isEdit.value = true
      await loadProduct(Number(id))
      console.log('产品加载完成')
    } else {
      console.log('创建模式')
    }
  } catch (error) {
    console.error('onMounted 错误:', error)
  }
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: var(--spacing-lg);
}

.card-header__titles {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.card-title {
  margin: 0;
  font-size: var(--font-size-xl);
  font-weight: var(--font-weight-semibold);
  color: var(--color-text-primary);
}

.card-subtitle {
  margin: 0;
  font-size: var(--font-size-sm);
  color: var(--color-text-tertiary);
}

/* 新增：模块卡片样式 */
.section-card {
  background: linear-gradient(135deg, #f8f9fb 0%, #fefefe 100%);
  border: 1px solid #e4e7ed;
  border-radius: 12px;
  padding: 28px 32px;
  margin-bottom: 28px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.section-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  border-color: #d0d4db;
}

.section-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 2px solid #e4e7ed;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-title .el-icon {
  font-size: 20px;
  color: #409eff;
}

.section-subtitle {
  font-size: 13px;
  color: #909399;
  margin: 0;
  line-height: 1.5;
}

/* 基本信息区域 */
.basic-info-section {
  background: linear-gradient(135deg, #e6f7ff 0%, #ffffff 100%);
  border-color: #91d5ff;
}

.basic-info-section:hover {
  border-color: #69c0ff;
}

/* 翻译区域 */
.translation-section {
  background: linear-gradient(135deg, #f0f5ff 0%, #ffffff 100%);
  border-color: #adc6ff;
}

.translation-section:hover {
  border-color: #85a5ff;
}

/* 变体区域 */
.variants-main-section {
  background: linear-gradient(135deg, #f6ffed 0%, #ffffff 100%);
  border-color: #b7eb8f;
}

.variants-main-section:hover {
  border-color: #95de64;
}

.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
  width: 178px;
  height: 178px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-uploader:hover {
  border-color: #409eff;
}

/* 让整个上传区域可点击 */
.clickable-upload :deep(.el-upload) {
  width: 100%;
  height: 100%;
  display: block;
}

.upload-area {
  width: 178px;
  height: 178px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.image-preview {
  width: 178px;
  height: 178px;
  object-fit: cover;
}

.image-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.variants-section {
  margin-top: 20px;
}

.variant-title {
  display: flex;
  align-items: center;
  width: 100%;
  font-weight: 600;
  font-size: 15px;
}

.variant-title > span:first-child {
  color: #409eff;
}

.variant-options {
  margin-left: 10px;
  color: #909399;
  font-size: 13px;
  font-weight: 400;
}

/* 优化变体折叠组件样式 */
.variants-section :deep(.el-collapse-item__header) {
  background: linear-gradient(135deg, #f0f9ff 0%, #ffffff 100%);
  border: 1px solid #bae7ff;
  border-radius: 8px;
  padding: 12px 16px;
  margin-bottom: 12px;
  transition: all 0.3s;
  font-weight: 500;
}

.variants-section :deep(.el-collapse-item__header:hover) {
  background: linear-gradient(135deg, #e6f7ff 0%, #f5fcff 100%);
  border-color: #91d5ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.1);
}

.variants-section :deep(.el-collapse-item__wrap) {
  border: none;
  background: transparent;
}

.variants-section :deep(.el-collapse-item__content) {
  padding: 20px 16px;
}

.variant-options-section {
  margin-bottom: 24px;
  padding: 20px;
  background: linear-gradient(135deg, #fff7e6 0%, #fffbf0 100%);
  border: 1px solid #ffe7ba;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(255, 193, 7, 0.1);
}

.variant-options-section h4 {
  margin: 0;
  font-size: 15px;
  font-weight: 600;
  color: #606266;
  display: flex;
  align-items: center;
  gap: 6px;
}

.subsection-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.subsection-header h4 {
  margin: 0;
}

.option-item {
  display: flex;
  align-items: center;
  margin-top: 12px;
  padding: 12px;
  background: #fff;
  border-radius: 6px;
  border: 1px solid #f0f0f0;
  transition: all 0.2s;
}

.option-item:hover {
  border-color: #ffc069;
  box-shadow: 0 2px 8px rgba(255, 193, 7, 0.15);
}

.variant-images {
  width: 100%;
}

.variant-image-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.variant-image-item {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.variant-image-item.primary .image-uploader {
  border-color: #409eff;
}

.variant-image-actions {
  margin-top: 8px;
  display: flex;
  gap: 8px;
}

.variant-image-actions .el-button {
  padding: 0 12px;
}

.variant-image-grid .add-card {
  align-self: flex-start;
}

.variant-specifications-section {
  margin-top: 24px;
  padding: 20px;
  background: linear-gradient(135deg, #e6fffb 0%, #f0fffe 100%);
  border: 1px solid #87e8de;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(19, 194, 194, 0.1);
}

.variant-specifications-section h4 {
  margin: 0;
  font-size: 15px;
  font-weight: 600;
  color: #606266;
  display: flex;
  align-items: center;
  gap: 6px;
}

.variant-specifications {
  margin-top: 0;
}

.spec-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-top: 12px;
}

.spec-item-row {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  align-items: center;
  padding: 12px;
  background: #fff;
  border-radius: 6px;
  border: 1px solid #f0f0f0;
  transition: all 0.2s;
}

.spec-item-row:hover {
  border-color: #5cdbd3;
  box-shadow: 0 2px 8px rgba(19, 194, 194, 0.15);
}

.spec-input {
  width: 200px;
}

.spec-empty {
  margin-top: 12px;
  color: #909399;
  font-size: 13px;
  text-align: center;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

/* 优化表单项间距 */
.section-card .el-form-item {
  margin-bottom: 22px;
}

/* 优化标签页样式 */
.translation-section :deep(.el-tabs--border-card) {
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border-radius: 8px;
}

.translation-section :deep(.el-tabs__header) {
  background: linear-gradient(135deg, #f0f5ff 0%, #fafbff 100%);
  border-bottom: 2px solid #d9e3ff;
  border-radius: 8px 8px 0 0;
}

.translation-section :deep(.el-tabs__item) {
  font-weight: 500;
}

.translation-section :deep(.el-tabs__item.is-active) {
  color: #409eff;
  font-weight: 600;
}

/* 优化提交按钮区域 */
.el-form-item:last-child {
  margin-top: 32px;
  padding-top: 24px;
  border-top: 2px solid #f0f0f0;
  margin-bottom: 0;
}

.el-form-item:last-child .el-button {
  min-width: 120px;
  height: 44px;
  font-size: 15px;
  font-weight: 500;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .section-card {
    padding: 20px 16px;
  }
  
  .section-title {
    font-size: 16px;
  }
  
  .option-item,
  .spec-item-row {
    flex-direction: column;
    align-items: stretch;
  }
  
  .option-item > *,
  .spec-input {
    width: 100% !important;
    margin-right: 0 !important;
  }
}
</style>
